package ch.uzh.ifi.seal.ssqa.metrics.keyvalue;

import java.util.HashMap;
import java.util.List;

import org.eclipse.emf.ecore.EObject;

import ch.uzh.ifi.seal.ssqa.model.Component;
import ch.uzh.ifi.seal.ssqa.model.DiagramComponent;
import ch.uzh.ifi.seal.ssqa.model.Module;
import ch.uzh.ifi.seal.ssqa.model.Source;
import ch.uzh.ifi.seal.ssqa.storage.IStorage;
import ch.uzh.ifi.seal.ssqa.storage.StorageResult;
import ch.uzh.ifi.seal.ssqa.storage.TeneoHibernateStorage;

public class IssueTypeKeyValueMetric implements IKeyValueMetric{

	HashMap<String, Integer> issueTypeCount = new HashMap<String, Integer>();

	private IStorage storage;

	public IssueTypeKeyValueMetric readOutData(EObject object) {
		this.storage = new TeneoHibernateStorage();
		if (object instanceof DiagramComponent) {

		} else if (object instanceof Component) {
			this.readOutComponent((Component) object);
		}
		return this;
	}

	private void readOutComponent(Component component) {
		String path = "";
		if (component instanceof Source) {
			Source source = (Source) component;
			path = source.getProjectPath();
		} else if (component instanceof Module) {
			Module module = (Module) component;
			path = module.getProjectPath();
		}

		if (path != "") {
			StorageResult result = this.storage
					.executeListSQLQuery("SELECT issue.type FROM `ssqa`.`issue` as issue "
							+ " JOIN `ssqa`.`revision` as revision on issue.id = revision.ucmactivity_ucmactivity_e_id"
							+ " WHERE revision.filepath = '" + path + "'");
			
			List<String> resultList = (List<String>) result.getListResult();

			for (String issue : resultList) {
				int count = 1;
				if (this.issueTypeCount.containsKey(issue)) {
					count = this.issueTypeCount.get(issue) + 1;
				}
				this.issueTypeCount.put(issue, count);
			}
			result.getSession().close();
		}
	}

	public HashMap<String, Integer> getResult() {
		return this.issueTypeCount;
	}
}
